package com.example.demo.util;

import com.example.demo.entity.admin;
import com.example.demo.mapperDao.AdminDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    AdminDao adminDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("授权-------------------------------------");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        admin admin= (com.example.demo.entity.admin) subject.getPrincipal();
        admin=adminDao.selectAdmin(new admin(0,admin.getUser(),"",0));
        if (admin.getType()==0){
            info.addStringPermission("user:1");
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        System.out.println("认证-------------------------------------");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        admin admin = adminDao.selectAdmin(new admin(0, userToken.getUsername(), "", 0));
         //查询有没有这个用户
        if (admin == null) {
            return null;
        }
        //shiro判断密码是否正确
        return new SimpleAuthenticationInfo(admin, admin.getPwd(), "");
    }
}
